package com.bqtv.sport.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.viewpager.widget.ViewPager.GONE
import androidx.viewpager.widget.ViewPager.VISIBLE
import com.bqtv.sport.R
import com.bqtv.sport.app.AppActivity
import com.bqtv.sport.commen.utils.ActivityManager
import com.bqtv.sport.commen.utils.DoubleClickHelper
import com.bqtv.sport.databinding.ActivityMainBinding
import com.bqtv.sport.ui.im.ChatAppModuleUtil
import com.bqtv.sport.ui.main.fragment.ContactFragment
import com.bqtv.sport.ui.main.fragment.HomeFragment
import com.bqtv.sport.ui.main.fragment.MatchFragment
import com.bqtv.sport.ui.main.fragment.MessageFragment
import com.bqtv.sport.ui.main.fragment.MineFragment
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.TabLayoutOnPageChangeListener
import com.gyf.immersionbar.ImmersionBar
import com.hjq.base.FragmentPagerAdapter
import com.hjq.base.http.HttpData
import com.hjq.http.EasyHttp
import com.hjq.http.listener.HttpCallbackProxy
import com.tencent.imsdk.v2.V2TIMFriendApplication
import com.tencent.imsdk.v2.V2TIMFriendApplicationResult
import com.tencent.imsdk.v2.V2TIMFriendshipListener
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tuicore.TUIConstants
import com.tencent.qcloud.tuikit.tuicontact.classicui.pages.TUIContactFragment
import com.tencent.qcloud.tuikit.tuiconversation.classicui.page.TUIConversationFragmentContainer

class MainActivity : AppActivity<ActivityMainBinding>() {
    companion object {
        //需要跳转的fragment
        private const val INTENT_KEY_IN_Index = "index"
        fun start(context: Context) {
            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }

    var mPagerAdapter: FragmentPagerAdapter<Fragment>? = null
    var mTitles: ArrayList<String> = ArrayList()
    private var mIconSelectIds: ArrayList<Int> = ArrayList()
    private var unreadCountReceiver: BroadcastReceiver? = null

    override fun getViewBinding() = ActivityMainBinding.inflate(layoutInflater)

//    override fun isStatusBarEnabled(): Boolean {
//        // 使用沉浸式状态栏
//        return !super.isStatusBarEnabled()
//    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        switchFragment(getInt(INTENT_KEY_IN_Index))
    }

    private fun switchFragment(fragmentIndex: Int) {
        if (fragmentIndex == -1) {
            return
        }
        when (fragmentIndex) {
            0, 1, 2, 3, 4 -> binding.viewPager.currentItem = fragmentIndex
            else -> {}
        }
    }

    override fun initView() {
        ChatAppModuleUtil.init(this)
        ImmersionBar.setTitleBarMarginTop(this, binding.viewPager)
        initUnreadCountReceiver()
    }
    override fun onResume() {
        super.onResume()
        registerUnreadListener()

    }

    override fun initData() {
        mTitles = ArrayList<String>()
        mTitles.add(getString(R.string.home))
        mTitles.add(getString(R.string.game))
        mTitles.add(getString(R.string.friend))
        mTitles.add(getString(R.string.msg))
        mTitles.add(getString(R.string.mine))

        mPagerAdapter = FragmentPagerAdapter(this)
        mPagerAdapter?.addFragment(HomeFragment())
        mPagerAdapter?.addFragment(MatchFragment())
        mPagerAdapter?.addFragment(ContactFragment())
        mPagerAdapter?.addFragment(MessageFragment())
        mPagerAdapter?.addFragment(MineFragment())

        mIconSelectIds = ArrayList()
        mIconSelectIds.add(R.drawable.tab_main_home)
        mIconSelectIds.add(R.drawable.tab_main_game)
        mIconSelectIds.add(R.drawable.tab_main_friend)
        mIconSelectIds.add(R.drawable.tab_main_msg)
        mIconSelectIds.add(R.drawable.tab_main_mine)
        binding.viewPager.adapter = mPagerAdapter
        binding.viewPager.addOnPageChangeListener(TabLayoutOnPageChangeListener(binding.tabs))
        binding.viewPager.offscreenPageLimit = 4
        //设置自定义tab
        for (i in mTitles.indices) {
            binding.tabs.addTab(binding.tabs.newTab())
            val tab: TabLayout.Tab = binding.tabs.getTabAt(i)!!
            if (tab != null) {
                tab.setCustomView(getTabView(i))
            }
        }
        binding.tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                binding.viewPager.setCurrentItem(tab!!.position)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })

//        triggerClearAllUnreadMessage()

        getVersion()
    }

    fun getVersion() {
      /*  EasyHttp.get(this)
            .api(GetVersionApi().apply {
                this.type = 1
            })
            .request(object : HttpCallbackProxy<HttpData<GetVersionBean>>(this) {
                override fun onHttpSuccess(data: HttpData<GetVersionBean>) {
                    data.data?.let {
                        setVersion(it)
                    }
                }
            })*/
    }

//    fun setVersion(data: GetVersionBean) {
//        if (data.versionCode.equals(AppConfig.getVersionName())) {
//            return
//        }
//        UpdateDialog.Builder(this).apply {
//            setVersionName(data.versionCode.toString())    // 版本名
//            setForceUpdate(false)  // 是否强制更新
//            setUpdateLog("")        // 更新日志
//            setDownloadUrl(data.venUrl)            // 下载 URL
//        }.show()
//    }

    private fun getTabView(pos: Int): View? {
        val view: View = LayoutInflater.from(getContext()).inflate(R.layout.tab_main, null)
        val iv_tab = view.findViewById<ImageView>(R.id.iv_tab_main)
        val tv_tab = view.findViewById<TextView>(R.id.tv_tab_main)
        iv_tab.setImageResource(mIconSelectIds.get(pos))
        tv_tab.text = mTitles[pos]
        return view
    }

    private fun setTabUnRead(pos: Int, num: Long) {
        val tab: TabLayout.Tab? = binding.tabs.getTabAt(pos)
        val tabView = tab?.customView
        val v_unread = tabView!!.findViewById<View>(R.id.v_unread)
        if (num == 0L) {
            v_unread.visibility = GONE
        } else {
            v_unread.visibility = VISIBLE
        }
    }

    private fun initUnreadCountReceiver() {
        unreadCountReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent) {
                setTabUnRead(3, intent.getLongExtra(TUIConstants.UNREAD_COUNT_EXTRA, 0))
            }
        }

        val unreadCountFilter = IntentFilter()
        unreadCountFilter.addAction(TUIConstants.CONVERSATION_UNREAD_COUNT_ACTION)
        LocalBroadcastManager.getInstance(this)
            .registerReceiver(unreadCountReceiver!!, unreadCountFilter)
    }

    private val friendshipListener: V2TIMFriendshipListener = object : V2TIMFriendshipListener() {
        override fun onFriendApplicationListAdded(applicationList: List<V2TIMFriendApplication>) {
            refreshFriendApplicationUnreadCount()
        }

        override fun onFriendApplicationListDeleted(userIDList: List<String>) {
            refreshFriendApplicationUnreadCount()
        }

        override fun onFriendApplicationListRead() {
            refreshFriendApplicationUnreadCount()
        }
    }

    private fun registerUnreadListener() {
        V2TIMManager.getFriendshipManager().addFriendListener(friendshipListener)
        refreshFriendApplicationUnreadCount()
    }

    private fun refreshFriendApplicationUnreadCount() {
        V2TIMManager.getFriendshipManager()
            .getFriendApplicationList(object : V2TIMValueCallback<V2TIMFriendApplicationResult> {
                override fun onSuccess(v2TIMFriendApplicationResult: V2TIMFriendApplicationResult) {
                    runOnUiThread {
                        setTabUnRead(2, v2TIMFriendApplicationResult.unreadCount.toLong())
                    }
                }

                override fun onError(code: Int, desc: String?) {}
            })
    }

    override fun onPause() {
        super.onPause()
        V2TIMManager.getFriendshipManager().removeFriendListener(friendshipListener)
    }

    override fun onBackPressed() {
        if (!DoubleClickHelper.isOnDoubleClick) {
            toast(R.string.home_exit_hint)
            return
        }

        // 移动到上一个任务栈，避免侧滑引起的不良反应
        moveTaskToBack(false)
        postDelayed({
            // 进行内存优化，销毁掉所有的界面
            ActivityManager.getInstance().finishAllActivities()
        }, 300)
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.viewPager.adapter = null
        if (unreadCountReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(unreadCountReceiver!!)
            unreadCountReceiver = null
        }
    }

}